package auth

import (
	"context"
	authpb "coolcar/auth/api/gen/v1"
	"coolcar/auth/dao"
	"time"

	"google.golang.org/grpc/codes"

	"google.golang.org/grpc/status"

	"go.uber.org/zap"
)

type Service struct {
	Logger *zap.Logger
	*authpb.UnimplementedAuthServiceServer
	OpenIdResolver OpenIdResolver
	Mongo          *dao.Mongo
	TokenGenarator TokenGenarator
	TokenExpire    time.Duration
}

type OpenIdResolver interface {
	Resolve(code string) (string, error)
}

type TokenGenarator interface {
	GenarateToken(accountID string, expire time.Duration) (string, error)
}

func (s *Service) Login(c context.Context, req *authpb.LoginRequest) (*authpb.LoginResponse, error) {
	openId, err := s.OpenIdResolver.Resolve(req.Code)
	if err != nil {
		return nil, status.Errorf(codes.Unavailable, "can not resolve openId", err)
	}
	accountID, err := s.Mongo.ResolveAccountID(c, openId)
	if err != nil {
		s.Logger.Error("can not resolve accountId:", zap.Error(err))
		return nil, status.Error(codes.Internal, "")
	}

	token, err := s.TokenGenarator.GenarateToken(accountID.String(), s.TokenExpire)
	if err != nil {
		s.Logger.Error("can not genatare token", zap.Error(err))
		return nil, status.Error(codes.Internal, "")
	}

	return &authpb.LoginResponse{
		AccessToken: token,
		ExpiresIn:   int32(s.TokenExpire.Seconds()),
	}, nil
}
